package com.transcasafe.eanpay.core.auth;

import com.transcasafe.eanpay.core.cipher.Signer;
import com.transcasafe.eanpay.core.http.HttpHeaders;
import com.transcasafe.eanpay.core.http.PayConstant;
import com.transcasafe.eanpay.core.util.ShaUtil;

import java.nio.charset.StandardCharsets;

public class EanPayCredential implements Credential {
    private final String mchNo;
    private final Signer signer;

    public EanPayCredential(String mchNo, Signer signer) {
        this.mchNo = mchNo;
        this.signer = signer;
    }

    @Override
    public String getMchNo() {
        return mchNo;
    }

    /**
     * SHA256(商户号 + "," + 时间戳 + "," + 随机数 + "," + HTTP Response Body + "," + mchKey)
     *
     * @param headers
     * @param signBody 用于签名的请求体
     * @return
     */
    @Override
    public String getAuthorization(HttpHeaders headers, String signBody) {
        StringBuilder sb = new StringBuilder();
        sb.append(mchNo);
        sb.append(",");
        sb.append(headers.getHeader(PayConstant.HTTP_HEADER_TIMESTAMP));
        sb.append(",");
        sb.append(headers.getHeader(PayConstant.HTTP_HEADER_NONCE));
        sb.append(",");
        sb.append(signBody);
        return signer.sign(sb.toString()).getSign();
    }
}
